package com.d.common.exception;

import com.d.common.utils.RT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;

@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理全局异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<RT> handleException(Exception e) {
        logger.debug("系统异常");
        e.printStackTrace();
        RT res = new RT(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
        return new ResponseEntity<>(res, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    /**
     * 处理校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseEntity<RT> handleException(MethodArgumentNotValidException e) {
        logger.debug("校验异常");
        e.printStackTrace();

        // 获取校验错误信息
        BindingResult bindingResult = e.getBindingResult();
        List<String> errorMsgs = new ArrayList<>();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            String errorMsg = fieldError.getDefaultMessage();
            errorMsgs.add(errorMsg);
        }
        // 将errorMsgs转换成字符串，用逗号隔开
        String errorMsgStr = String.join(",", errorMsgs);

        RT res = new RT(HttpStatus.BAD_REQUEST.value(), errorMsgStr);
        return new ResponseEntity<>(res, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public RT handleBindException(ConstraintViolationException ex) {
        String message = StringUtils.isEmpty(ex.getLocalizedMessage()) ? "参数异常":ex.getLocalizedMessage();
        return RT.error(400, message);
    }

    /**
     * 处理自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(RRException.class)
    @ResponseBody
    public ResponseEntity<RT> handleException(RRException e) {
        logger.debug("自定义异常",e.getMsg());
        RT res = new RT(e.getCode(), e.getMsg());
        return new ResponseEntity<>(res, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
